package com.ffcs.web.controllers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.ffcs.web.model.dto.AccessToken4Code;
import com.ffcs.web.model.dto.BaseResponse;
import com.ffcs.web.model.dto.CounselorOrder;
import com.ffcs.web.model.dto.MyOrderResponse;
import com.ffcs.web.model.dto.OrderListResponse;
import com.ffcs.web.model.dto.OrderResponse;
import com.ffcs.web.model.dto.ShouyiResponse;
import com.ffcs.web.model.dto.UserInfo;
import com.ffcs.web.model.entity.Counselor;
import com.ffcs.web.model.entity.Drawal;
import com.ffcs.web.model.entity.Order;
import com.ffcs.web.model.entity.Study;
import com.ffcs.web.model.entity.WxUser;
import com.ffcs.web.model.entity.YuyueTemp;
import com.ffcs.web.model.requests.AddOrderRequest;
import com.ffcs.web.services.AuthCodeService;
import com.ffcs.web.services.CounselorService;
import com.ffcs.web.services.FreeAskService;
import com.ffcs.web.services.MessageService;
import com.ffcs.web.services.OrderService;
import com.ffcs.web.services.StudyService;
import com.ffcs.web.services.WxUserService;
import com.ffcs.web.utils.CommonConfig;
import com.ffcs.web.utils.HttpGetUtil;
import com.ffcs.web.utils.JsSign;
import com.ffcs.web.utils.JsonUtil;
import com.ffcs.web.utils.Refund;
import com.ffcs.web.utils.WxJsDemo;
import com.ffcs.web.utils.RequestHandler;

@Controller
public class OrderController {
	
	private Logger logger = Logger.getLogger(OrderController.class);
	
	private static String appsecret = CommonConfig.getProperty("APPSECRET");
	//这个参数partnerkey是在商户后台配置的一个32位的key,微信商户平台-账户设置-安全设置-api安全
	private static String partnerkey = CommonConfig.getProperty("PARTNERKEY");
	@Autowired
	private OrderService orderService;
	@Autowired
	private StudyService studyService;
	@Autowired
	private CounselorService counselorService;
	@Autowired
	private AuthCodeService authCodeService;
	@Autowired
	private WxUserService wxUserService;
	@Autowired
	private FreeAskService freeAskService;
	@Autowired
	private MessageService messageService;
	
	/**
	 * 生成咨询订单
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("addOrder")
	@ResponseBody
	public void addOrder(HttpServletRequest request,HttpServletResponse response,AddOrderRequest addOrderRequest,String orderSn) throws IOException, ServletException{
		if(null!=orderSn && !"".equals(orderSn)){
			//获取网页授权code
			String redirect_uri=CommonConfig.getProperty("REDIRECT_URI");
			String appid=CommonConfig.getProperty("APPID");
			String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_base&state="+orderSn+"#wechat_redirect";
			response.sendRedirect(url);
//			request.getRequestDispatcher("payOrder.jsp").forward(request, response);
		}else{
			Order order=null;
			WxUser wuser=(WxUser) request.getSession().getAttribute("wxUser");
			try {
				order=orderService.saveOrder(wuser,addOrderRequest);	
				logger.info("[orderSn="+order.getOrderSn()+"]生成订单成功，状态为待支付");
			} catch (Exception e) {
				logger.error("userid="+wuser.getId()+",userName="+wuser.getNickname()+"生成订单失败");
				e.printStackTrace();
			}
			
//			SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			order.setDateAddStr(sdf2.format(order.getDateAdd()));
//			Study study=studyService.getStudyDesc(addOrderRequest.getStudyId());
//			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//			study.setStartStudyStr(sdf.format(study.getStartStudy()));
//			study.setEndStudyStr(sdf.format(study.getEndStudy()));
//			request.setAttribute("study",study);
//			request.setAttribute("order",order);
			
			//获取网页授权code
			String redirect_uri=CommonConfig.getProperty("REDIRECT_URI");
			String appid=CommonConfig.getProperty("APPID");
			String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_base&state="+order.getOrderSn()+"#wechat_redirect";
			response.sendRedirect(url);
//			request.getRequestDispatcher("payOrder.jsp").forward(request, response);
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException 
	 */
	@RequestMapping("gotoOrderDesc")
	public void gotoOrderDesc(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
		String orderId=request.getParameter("orderId");
		Order order=orderService.getOrder(Integer.parseInt(orderId));
		if(null!=order.getSchoolAge()){
		if(order.getSchoolAge()==1){
			order.setSchoolAgeStr("0-3岁");
		}else if(order.getSchoolAge()==2){
			order.setSchoolAgeStr("幼儿园");
		}else if(order.getSchoolAge()==3){
			order.setSchoolAgeStr("小学1年级");
		}else if(order.getSchoolAge()==4){
			order.setSchoolAgeStr("小学2-5年级");
		}else if(order.getSchoolAge()==5){
			order.setSchoolAgeStr("小学毕业班");
		}else if(order.getSchoolAge()==6){
			order.setSchoolAgeStr("初中1-2年级");
		}else if(order.getSchoolAge()==7){
			order.setSchoolAgeStr("初中毕业班");
		}else if(order.getSchoolAge()==8){
			order.setSchoolAgeStr("高中1-2年级");
		}else if(order.getSchoolAge()==9){
			order.setSchoolAgeStr("高中毕业班");
		}else if(order.getSchoolAge()==10){
			order.setSchoolAgeStr("大学期间");
		}
		}else{
			order.setSchoolAgeStr("");
		}
		
		if(order.getQuestionDesc().contains("mp3")){
			request.setAttribute("isYuyin", 1);
		}else{
			request.setAttribute("isYuyin", 0);
		}
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar ca=Calendar.getInstance();
		ca.setTime(order.getDateAdd());
		ca.add(Calendar.SECOND, 9);
		order.setPayTime(sdf.format(ca.getTime())+".0");
		if(order.getQuestionDesc().contains("mp3")){
			order.setQuestionDesc(CommonConfig.getProperty("YUYIN_URL_FRONT")+order.getQuestionDesc());
		}
		request.setAttribute("order",order);
		Counselor counselor=counselorService.getCounselor(order.getCounseTel());
		counselor.setPersonHead(CommonConfig.getProperty("PIC_URL_FRONT")+counselor.getPersonHead());
		request.setAttribute("counselor",counselor);
		WxUser user=wxUserService.getUserByUserId(order.getUserId());
		request.setAttribute("user",user);
		request.getRequestDispatcher("business/myzixundesc.jsp").forward(request, response);
	}
	
	/**
	 * 补充订单资料
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping("gotobuPersonzl")
	@ResponseBody
	public void gotobuPersonzl(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String orderSn=request.getParameter("orderSn");
		String customerName=request.getParameter("customerName");
		String telephone=request.getParameter("telephone");
		//获取用户年龄
		String age=request.getParameter("age");
		//获取用户学龄
		String schoolAge=request.getParameter("schoolAge");
		//获取用户性别
		String sex=request.getParameter("sex");
		//获取用户婚姻状况
		String marr=request.getParameter("marr");
		
		orderService.buChongOrder(orderSn,age,schoolAge,sex,marr,customerName,telephone);
		response.sendRedirect("myOrder.jsp");
	}
	
	/**
	 * 获取我的订单接口
	 * @param request
	 * @param response
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("getMyCounselorOrder")
    @ResponseBody
    public OrderListResponse getMyCounselorOrder(HttpServletRequest request) throws IllegalAccessException, InvocationTargetException{
		OrderListResponse myOrderResponse=new OrderListResponse();
		
		//TODO判断session
		if(null==request.getSession().getAttribute("counseTel") || "".equals(request.getSession().getAttribute("counseTel"))){
			myOrderResponse.setResultCode("-1");
			myOrderResponse.setResultDesc("咨询师登录超时");
			return myOrderResponse;
		}
		String counseTel=(String)request.getSession().getAttribute("counseTel");
		
		myOrderResponse.setResultCode("0");
		myOrderResponse.setResultDesc("success");
		String orderStatus=request.getParameter("orderStatus");
		String orderType=request.getParameter("orderType");
		List<Order> orderList=orderService.getMyCounselorOrder(counseTel,orderStatus,orderType);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		for (Order order : orderList) {
			order.setBookTimeStr(sdf.format(order.getBookTime()));
			if(order.getQuestionDesc().contains("mp3")){
				order.setQuestionDesc(CommonConfig.getProperty("YUYIN_URL_FRONT")+order.getQuestionDesc());
			}
		}
		myOrderResponse.setOrderList(orderList);
		return myOrderResponse;
	}
	
	/**
	 * 获取我的订单接口
	 * @param request
	 * @param response
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("getMyOrder")
    @ResponseBody
    public MyOrderResponse getMyOrder(HttpServletRequest request) throws IllegalAccessException, InvocationTargetException{
		MyOrderResponse myOrderResponse=new MyOrderResponse();
		myOrderResponse.setResultCode("0");
		myOrderResponse.setResultDesc("success");
		String orderStatus=request.getParameter("orderStatus");
		WxUser wxUser=(WxUser)request.getSession().getAttribute("wxUser");
		List<Order> orderList=orderService.getOrderbyUserId(wxUser.getId(),orderStatus);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		for (Order order : orderList) {
			order.setBookTimeStr(sdf.format(order.getBookTime()));
			if(order.getQuestionDesc().contains("mp3")){
				order.setQuestionDesc(CommonConfig.getProperty("YUYIN_URL_FRONT")+order.getQuestionDesc());
			}
		}
//		for (Order counselor : orderList) {
//			if(null!=counselor.getGoodDirection()){
//				String gd="";
//				if(counselor.getGoodDirection().contains("1")){
//					gd+="学业倦怠,";
//				}
//				if(counselor.getGoodDirection().contains("2")){
//					gd+="亲子关系,";
//				}
//				if(counselor.getGoodDirection().contains("3")){
//					gd+="教育理念,";
//				}
//				if(counselor.getGoodDirection().contains("4")){
//					gd+="学习习惯,";
//				}
//				if(counselor.getGoodDirection().contains("5")){
//					gd+="人际关系,";
//				}
//				if(counselor.getGoodDirection().contains("6")){
//					gd+="沉迷网络,";
//				}
//				if(counselor.getGoodDirection().contains("7")){
//					gd+="情绪管理,";
//				}
//				if(counselor.getGoodDirection().contains("8")){
//					gd+="自控能力,";
//				}
//				gd=gd.substring(0, gd.length()-1);
//				counselor.setGoodDirection(gd);
//			}else{
//				counselor.setGoodDirection("");
//			}
//			counselor.setPersonHead(CommonConfig.getProperty("PIC_URL_FRONT")+counselor.getPersonHead());
//		}
		myOrderResponse.setOrderList(orderList);
		return myOrderResponse;
	}
	
	
	/**
	 * 网页获取code等授权接口
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("wxRedirectUri")
	@ResponseBody
	public void wxRedirectUri(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		String code=request.getParameter("code");
		String orderSn=request.getParameter("state");
		String tempValue=bestfuzhouForm(code);
		JSONObject jsonObj = JSONObject.fromObject(tempValue);
		
		String openId = "";
		String access_token = "";//获取用户信息的access_token
		String nickname = "";
		String refresh_token = "";
		String expires_in = "";
		
		if (jsonObj.containsKey("errcode")) {
			logger.info("支付获取openid出现异常");
			return ;
		} else {
			openId = jsonObj.getString("openid");
			access_token = jsonObj.getString("access_token");
			refresh_token = jsonObj.getString("refresh_token");
			expires_in = jsonObj.getString("expires_in");
		}
		Order order=orderService.getOrder(orderSn);
		String packages=WxJsDemo.getPayInfo(openId,order);
		jsonObj = JSONObject.fromObject("{"+packages+"}");
		String appId = jsonObj.getString("appId");
		String timeStamp = jsonObj.getString("timeStamp");
		String nonceStr = jsonObj.getString("nonceStr");
		String package1 = jsonObj.getString("package");
		String signType = jsonObj.getString("signType");
		String paySign = jsonObj.getString("paySign");		
		request.setAttribute("appId",appId);
		request.setAttribute("timeStamp",timeStamp);
		request.setAttribute("nonceStr",nonceStr);
		request.setAttribute("package1",package1);
		request.setAttribute("signType",signType);
		request.setAttribute("paySign",paySign);
		
		SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		order.setDateAddStr(sdf2.format(order.getDateAdd()));
		
		if(null!=order.getStudyId() && !"".equals(order.getStudyId())){
			Study study=studyService.getStudyDesc(order.getStudyId()+"");
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			study.setStartStudyStr(sdf.format(study.getStartStudy()));
			study.setEndStudyStr(sdf.format(study.getEndStudy()));
			request.setAttribute("study",study);
			request.setAttribute("order",order);
			request.getSession().setAttribute("orderSn",order.getOrderSn());
			request.getRequestDispatcher("payOrder.jsp").forward(request, response);
		}

		if(order.getOrderType().equals("1")){
			Counselor counselor=counselorService.getCounselor(order.getCounseTel());
			if(null!=counselor.getGoodDirection()){
				String gd="";
				if(counselor.getGoodDirection().contains("1")){
					gd+="学业倦怠,";
				}
				if(counselor.getGoodDirection().contains("2")){
					gd+="亲子关系,";
				}
				if(counselor.getGoodDirection().contains("3")){
					gd+="教育理念,";
				}
				if(counselor.getGoodDirection().contains("4")){
					gd+="学习习惯,";
				}
				if(counselor.getGoodDirection().contains("5")){
					gd+="人际关系,";
				}
				if(counselor.getGoodDirection().contains("6")){
					gd+="沉迷网络,";
				}
				if(counselor.getGoodDirection().contains("7")){
					gd+="情绪管理,";
				}
				if(counselor.getGoodDirection().contains("8")){
					gd+="自控能力,";
				}
				gd=gd.substring(0, gd.length()-1);
				counselor.setGoodDirection(gd);
			}else{
				counselor.setGoodDirection("");
			}
			counselor.setPersonHead(CommonConfig.getProperty("PIC_URL_FRONT")+counselor.getPersonHead());
			request.setAttribute("counselor",counselor);
			request.getSession().setAttribute("orderSn",order.getOrderSn());
			request.setAttribute("order",order);
			request.getRequestDispatcher("confirmYuyueOrder.jsp").forward(request, response);
		}
	}
	
	/**
	 * notifyurl
	 */
	@RequestMapping("notifyurl")
	@ResponseBody
	public String notifyurl(HttpServletRequest request){
		String res="";
		String line = "";
		BufferedReader reader;
		try {
			reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
			for (line = reader.readLine(); line != null; line = reader.readLine()) {
				res += line;
			}
			System.out.println("微信支付成功后台推送工单数据"+res);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
		
		Map<String,String> map=xmlParse(res);
        String appid=map.get("appid");
        String bank_type=map.get("bank_type");
        String cash_fee=map.get("cash_fee");
        String fee_type=map.get("fee_type");
        String is_subscribe=map.get("is_subscribe");
        String mch_id=map.get("mch_id");
        String nonce_str=map.get("nonce_str");
        String openid=map.get("openid");
        String out_trade_no=map.get("out_trade_no");
        logger.info("微信支付成功通知订单号out_trade_no="+out_trade_no);
        
        String result_code=map.get("result_code");
        String return_code=map.get("return_code");
        String sign=map.get("sign");
        String time_end=map.get("time_end");
        String total_fee=map.get("total_fee");
        String trade_type=map.get("trade_type");
        String transaction_id=map.get("transaction_id");
        
        //保存支付流水记录
        orderService.addWeixinStream(appid,bank_type,cash_fee,fee_type,is_subscribe,mch_id,nonce_str,openid,out_trade_no
        		,result_code,return_code,sign,time_end,time_end,total_fee,trade_type,transaction_id);
        
        
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", appid);
		packageParams.put("bank_type", bank_type);
		packageParams.put("cash_fee", cash_fee);
		packageParams.put("fee_type", fee_type);
		packageParams.put("is_subscribe", is_subscribe);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("openid", openid);
		packageParams.put("out_trade_no", out_trade_no);
		packageParams.put("result_code", result_code);
		packageParams.put("return_code", return_code);
		packageParams.put("time_end", time_end);
		packageParams.put("total_fee", total_fee);
		packageParams.put("trade_type", trade_type);
		packageParams.put("transaction_id", transaction_id);
        RequestHandler reqHandler = new RequestHandler(null, null);
		reqHandler.init(appid, appsecret, partnerkey);
		String reSign=reqHandler.createSign(packageParams);
		if(reSign.equals(sign)){
			
			orderService.updateOrderStatus(out_trade_no);
			
			Order order =orderService.getOrder(out_trade_no);
			if(order.getOrderType().equals("1")){
				orderService.updateCanYuyue(order);
				logger.info("订单为预约订单，将预约表"+order.getCounseTel()+"--"+order.getBookTimeStr()+"设置为已占用");
			}else{
				studyService.updateStudy(order.getStudyId());
			}
			logger.info("返回给微信success");
			return "success";
		}else{
			logger.error("返回给微信校验签名失败");
			return "error";
		}
		
	}
	
	/**
	 * 获取openid
	 * @param request
	 * @param response
	 * @param code
	 * @return
	 */
	public String bestfuzhouForm(String code){
		String appid = CommonConfig.getProperty("APPID");
		String appSecret = CommonConfig.getProperty("APPSECRET");		
		String oauthUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?&grant_type=authorization_code"; 
		String string = HttpGetUtil.doGet2(oauthUrl + "&code=" + code
				+ "&appid=" + appid + "&secret=" + appSecret,"");
		return string;
	}
	
	public String getOpenId(String code){
		String appid = CommonConfig.getProperty("APPID");
		String appSecret = CommonConfig.getProperty("APPSECRET");		
		String oauthUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?&grant_type=authorization_code"; 
		String string = HttpGetUtil.doGet2(oauthUrl + "&code=" + code
				+ "&appid=" + appid + "&secret=" + appSecret,"");
		return string;
	}
	
	/**
	 * 字符串转map
	 * @param protocolXML
	 * @return
	 */
	public Map xmlParse(String protocolXML) {  
		Map<String,String> map=new HashMap<String, String>();
        try {  
             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
             DocumentBuilder builder = factory.newDocumentBuilder();  
             Document doc = builder.parse(new InputSource(new StringReader(protocolXML)));  
             Element root = doc.getDocumentElement();  
             NodeList books = root.getChildNodes();   
             if (books != null) {  
                for (int i = 0; i < books.getLength(); i++) {  
                     Node book = books.item(i);  
                     map.put(book.getNodeName(),book.getFirstChild().getNodeValue());  
                 }  
             }  
         } catch (Exception e) {  
             e.printStackTrace();  
         }  
        return map;
     }   
	
	@RequestMapping("gotoTixianjilu")
	public void gotoTixianjilu(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		if(null==request.getSession().getAttribute("counseTel") || "".equals((String) request.getSession().getAttribute("counseTel"))){
			response.sendRedirect("business/login.jsp");
			return ;
		}
		String counseTel=(String) request.getSession().getAttribute("counseTel");
		List<Drawal> list=orderService.getTixianJilu(counseTel);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (Drawal drawal : list) {
			drawal.setDateStr(sdf.format(drawal.getDate()));
		}
		request.setAttribute("drawalList",list);
		request.getRequestDispatcher("business/tixianjilu.jsp").forward(request, response);
	}
	/**
	 * 跳完我的收入
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("gotoMyShoulu")
	public void gotoMyShoulu(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		if(null==request.getSession().getAttribute("counseTel") || "".equals((String) request.getSession().getAttribute("counseTel"))){
			response.getWriter().print("<script>alert('登录超时，请重新登录')</script>");
			response.sendRedirect("business/login.jsp");
			return ;
		}
		
		String counseTel=(String) request.getSession().getAttribute("counseTel");
		String yuer=orderService.getMyYuer(counseTel);
		request.setAttribute("yuer",yuer);
		request.getRequestDispatcher("business/myShoulu.jsp").forward(request, response);
	}
	
	@RequestMapping("getShouyi")
	@ResponseBody
	public ShouyiResponse getShouyi(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		ShouyiResponse shouyiResponse=new ShouyiResponse();
		String counseTel=(String) request.getSession().getAttribute("counseTel");
		shouyiResponse.setResultCode("0");
		shouyiResponse.setResultDesc("success");
		shouyiResponse.setYesterday(orderService.getYesterday(counseTel,"1"));
		shouyiResponse.setaWeek(orderService.getYesterday(counseTel,"7"));
		shouyiResponse.setaMonth(orderService.getYesterday(counseTel,"30"));
		shouyiResponse.setTotal(orderService.getYesterday(counseTel,"300"));
		return shouyiResponse;
	}
	
	@RequestMapping("gotoMinxian")
	public void gotoMinxian(HttpServletRequest request,HttpServletResponse response,String flag) throws ServletException, IOException{
		String counseTel=(String) request.getSession().getAttribute("counseTel");
		request.setAttribute("totalFee",orderService.getYesterday(counseTel,flag));
		List<Order> orderList=orderService.getOrderList(counseTel,flag);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		for (Order order : orderList) {
			order.setBookTimeStr(sdf.format(order.getDateChange()));
		}
		request.setAttribute("orderList",orderList);
		request.getRequestDispatcher("business/13.jsp").forward(request, response);
	}
	
	/**
	 * 新增体现记录
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("gotoTixian")
	@ResponseBody
	public BaseResponse gotoTixian(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		BaseResponse baseResponse=new BaseResponse();
		String counseTel=(String) request.getSession().getAttribute("counseTel");
		String code=request.getParameter("code");
		String money=request.getParameter("money");
		String account=request.getParameter("account");
		String bankName=request.getParameter("bankName");
		String payChannel=request.getParameter("payChannel");
		
		if(!authCodeService.isAuthCode(counseTel, code)){
			logger.info("验证码错误");
			baseResponse.setResultCode("-2");
    		baseResponse.setResultDesc("验证码错误");
    		return baseResponse;
		}
		
		String yuer=orderService.getMyYuer(counseTel);
		if(Double.parseDouble(money)>Double.parseDouble(yuer)){
			logger.info("体现余额大于系统余额");
			baseResponse.setResultCode("-2");
    		baseResponse.setResultDesc("提现余额大于系统余额");
    		return baseResponse;
		}
		
		Counselor counselor=counselorService.getCounselor(counseTel);
		
		try {
			orderService.addTixian(money,account,bankName,payChannel,counselor);
		} catch (Exception e) {
			baseResponse.setResultCode("-1");
    		baseResponse.setResultDesc("提现失败");
    		return baseResponse;
		}
		
		baseResponse.setResultCode("0");
		baseResponse.setResultDesc("success");
		return baseResponse;
	}

	@RequestMapping("gotoYuyueOrderForBind")
	public void gotoYuyueOrderForBind(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		String counseTel=request.getParameter("counseTel");
		String question=request.getParameter("question");
		String type=request.getParameter("type");
		String counseType=request.getParameter("counseType");
		String bookTime=request.getParameter("bookTime");
		String bookDay=request.getParameter("bookDay");
		String buyTime=request.getParameter("buyTime");
		WxUser wuser=(WxUser) request.getSession().getAttribute("wxUser");
		YuyueTemp yuyueTemp=orderService.addYuYueTemp(counseTel,question,counseType,bookTime,bookDay,buyTime,wuser,type);
		wuser=wxUserService.getUserByUserId(wuser.getId());
		logger.info("wuser.getTelephone()="+wuser.getTelephone()+"是否绑定了");
		request.getSession().setAttribute("wxUser",wuser);
		if(null==wuser.getTelephone() || "".equals(wuser.getTelephone())){
			response.sendRedirect("yuyueOrderBindjsp.jsp?yuyueId="+yuyueTemp.getId());
			return ;
		}else{
			Counselor counselor=counselorService.getCounselor(yuyueTemp.getCounseTel());
			if(null!=counselor.getGoodDirection()){
				String gd="";
				if(counselor.getGoodDirection().contains("1")){
					gd+="学业倦怠,";
				}
				if(counselor.getGoodDirection().contains("2")){
					gd+="亲子关系,";
				}
				if(counselor.getGoodDirection().contains("3")){
					gd+="教育理念,";
				}
				if(counselor.getGoodDirection().contains("4")){
					gd+="学习习惯,";
				}
				if(counselor.getGoodDirection().contains("5")){
					gd+="人际关系,";
				}
				if(counselor.getGoodDirection().contains("6")){
					gd+="沉迷网络,";
				}
				if(counselor.getGoodDirection().contains("7")){
					gd+="情绪管理,";
				}
				if(counselor.getGoodDirection().contains("8")){
					gd+="自控能力,";
				}
				gd=gd.substring(0, gd.length()-1);
				counselor.setGoodDirection(gd);
			}else{
				counselor.setGoodDirection("");
			}
			counselor.setPersonHead(CommonConfig.getProperty("PIC_URL_FRONT")+counselor.getPersonHead());
			request.setAttribute("counselor",counselor);
			request.setAttribute("yuyueTemp",yuyueTemp);
			request.getRequestDispatcher("yuyueOrder.jsp").forward(request, response);
		}

	}
	
	@RequestMapping("gotoYuyueOrder")
	public void gotoYuyueOrder(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		String telphone=request.getParameter("telphone");
		String yuyueId=request.getParameter("yuyueId");
		WxUser wxUser=(WxUser) request.getSession().getAttribute("wxUser");
		wxUserService.bindUser(wxUser, telphone);
		YuyueTemp yuyueTemp=orderService.getYuyueTemp(yuyueId);
		Counselor counselor=counselorService.getCounselor(yuyueTemp.getCounseTel());
		if(null!=counselor.getGoodDirection()){
			String gd="";
			if(counselor.getGoodDirection().contains("1")){
				gd+="学业倦怠,";
			}
			if(counselor.getGoodDirection().contains("2")){
				gd+="亲子关系,";
			}
			if(counselor.getGoodDirection().contains("3")){
				gd+="教育理念,";
			}
			if(counselor.getGoodDirection().contains("4")){
				gd+="学习习惯,";
			}
			if(counselor.getGoodDirection().contains("5")){
				gd+="人际关系,";
			}
			if(counselor.getGoodDirection().contains("6")){
				gd+="沉迷网络,";
			}
			if(counselor.getGoodDirection().contains("7")){
				gd+="情绪管理,";
			}
			if(counselor.getGoodDirection().contains("8")){
				gd+="自控能力,";
			}
			gd=gd.substring(0, gd.length()-1);
			counselor.setGoodDirection(gd);
		}else{
			counselor.setGoodDirection("");
		}
		counselor.setPersonHead(CommonConfig.getProperty("PIC_URL_FRONT")+counselor.getPersonHead());
		request.setAttribute("counselor",counselor);
		request.setAttribute("yuyueTemp",yuyueTemp);
		request.getRequestDispatcher("yuyueOrder.jsp").forward(request, response);
		
	}
	
	@SuppressWarnings("unused")
	@RequestMapping("addYuyueOrder")
	@ResponseBody
	public void addYuyueOrder(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
		String yuyueId=request.getParameter("yuyueId");
		Order order=null;
		WxUser wuser=(WxUser) request.getSession().getAttribute("wxUser");
		YuyueTemp yuyueTemp=orderService.getYuyueTemp(yuyueId);
		try {
			order=orderService.saveOrder(yuyueId,wuser);	
			logger.info("[orderSn="+order.getOrderSn()+"]生成订单成功，状态为待支付");
		} catch (Exception e) {
			logger.error("userid="+wuser.getId()+",userName="+wuser.getNickname()+"生成订单失败");
			response.sendRedirect("gotoyuyuejsp?tel="+yuyueTemp.getCounseTel()+"&errorMsg=error");
			return ;
		}
		
		if(null==order){
			logger.error("userid="+wuser.getId()+",userName="+wuser.getNickname()+"生成订单失败");
			response.sendRedirect("gotoyuyuejsp?tel="+yuyueTemp.getCounseTel()+"&errorMsg=error");
			return ;
		}
		
		//获取网页授权code
		String redirect_uri=CommonConfig.getProperty("REDIRECT_URI");
		String appid=CommonConfig.getProperty("APPID");
		String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_base&state="+order.getOrderSn()+"#wechat_redirect";
		response.sendRedirect(url);
		
//		request.getRequestDispatcher("payOrder.jsp").forward(request, response);
	}
	
	/*
	 * 获取培训报名情况
	 */
	@RequestMapping("getBaoming")
	@ResponseBody
	public OrderListResponse getBaoming(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
		String studyId=request.getParameter("studyId");
		String getBaoming=request.getParameter("getBaoming");
		OrderListResponse orderListResponse=new OrderListResponse();
		orderListResponse.setResultCode("0");
		orderListResponse.setResultDesc("success");
		List<Order> orderList=orderService.getBaoming(studyId,getBaoming);
//		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
//		for (Order order : orderList) {
//			order.setBookTimeStr(sdf.format(order.getBookTime()));
//		}
		orderListResponse.setOrderList(orderList);
		return orderListResponse;
		
	}
	/*
	 * 获取培训报名情况
	 */
	@RequestMapping("gotoPingjiaOrder")
	public void gotoPingjiaOrder(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
		String orderSn=request.getParameter("orderSn");
		String pingjiaxx=request.getParameter("pingjiaxx");
		String pingjia=request.getParameter("pingjia");
		orderService.pingjiaOrder(orderSn,pingjiaxx,pingjia);
		
		if(null!=request.getParameter("studyId") && !"".equals(request.getParameter("studyId"))){
			String studyId=request.getParameter("studyId");
			response.sendRedirect("peixunAllPingLun.jsp?studyId="+studyId);
			return;
		}
		response.sendRedirect("myOrder.jsp");
		return;
	}
	
	/**
	 * 去我的培训订单详情页
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("gotoPeiXunOrderDesc")
	public void gotoPeiXunOrderDesc(HttpServletRequest request,HttpServletResponse response,String orderId) throws IOException, ServletException{
		Order order=orderService.getOrder(Integer.parseInt(orderId));
		SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		order.setDateAddStr(sdf2.format(order.getDateAdd()));
		request.setAttribute("order",order);
		Study study=studyService.getStudyDesc(order.getStudyId()+"");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		study.setStartStudyStr(sdf.format(study.getStartStudy()));
		study.setEndStudyStr(sdf.format(study.getEndStudy()));
		request.setAttribute("study",study);
		request.getRequestDispatcher("business/peixunOrderDesc.jsp").forward(request, response);
	}
	
	/**
	 * 更新培训订单状态，涉及退款
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("updatePeixunOrder")
	@ResponseBody
	public BaseResponse updatePeixunOrder(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
		String orderId=request.getParameter("orderId");
		String openType=request.getParameter("openType");
		String mark=request.getParameter("mark");
		BaseResponse baseResponse=new BaseResponse();
		Order order=orderService.getOrder(Integer.parseInt(orderId));
		try {
			if("1".equals(openType)){
				if(!"1".equals(order.getOrderType())){
					orderService.updatePeixunOrder(orderId,"2");
				}else{
					orderService.updatePeixunOrder(orderId,"2");
				}
				wxUserService.updateUser(order);
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
				String content="(订单已结算)<br/> 您好，您在"+sdf.format(order.getDateAdd())+"的下的单已被咨询师"+order.getCounseTel()+"结算!,您可前去我的订单列表进行评价";
				messageService.inserSystemMessage(order.getUserId(),"2",content);
			}else{
				
				orderService.updatePeixunOrder(orderId,mark,order.getOrderPrice());
				orderService.updatePeixunOrder(orderId,mark,order.getOrderPrice());
				Refund refund=new Refund();
				String refundMark=refund.wechatRefund(order.getOrderSn(),(int)(order.getOrderPrice()*100)+"",(int)(order.getOrderPrice()*100)+"");
				orderService.updateOrderFailure(orderId,refundMark);
				//集训或培训 已报人数减1
				logger.info("orderType="+order.getOrderType()+"如果为2或3 能删减报名人数");
				if(!"1".equals(order.getOrderType())){
					logger.info("orderType="+order.getOrderType()+"如果为2或3 能删减报名人数");
					studyService.updateJianStudy(order.getStudyId());
//					SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
//					String content="(免费提问待回复)<br/> 您好，有一个在"+sdf.format(freeAsk.getAskTime())+"的提问正等待您的回复!";
//					messageService.inserSystemMessage(freeAsk.getUserId(), type,content);
				}
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
				String content="(订单被拒绝)<br/> 您好，您在"+sdf.format(order.getDateAdd())+"的下的单已被咨询师"+order.getCounseTel()+"拒绝!如有疑问请联系管理员";
				messageService.inserSystemMessage(order.getUserId(),"2",content);
			}
		} catch (Exception e) {
			e.printStackTrace();
			baseResponse.setResultCode("-1");
			baseResponse.setResultDesc("变更订单状态失败");
			return baseResponse;
		}
		baseResponse.setResultCode("0");
		baseResponse.setResultDesc("success");
		logger.info("orderId="+orderId+"变更订单状态成功");
		return baseResponse;
		
	}
	
	
	@RequestMapping("deleteOrder")
	@ResponseBody
	public void deleteOrder(HttpServletRequest request,HttpServletResponse response,String orderId) throws IOException{
		orderService.deleteOrder(orderId);
		logger.info("orderId="+orderId+"订单取消成功");
		response.sendRedirect("myOrder.jsp?param=deleteOrder");
	}
	
	public static void main(String[] args) {
		Double d=0.01d;
		System.out.println((int)(d*100));
	}
	
}
